<?php

namespace App\Http\Controllers\Cron;

use App\Http\Controllers\Controller;
use App\Models\ActionLog;
use App\Models\Blacklist;
use Illuminate\Support\Facades\DB;

class BlacklistController extends Controller
{

    /**
     * 黑名单计划任务
     */
    public function blacklist()
    {
        $max = 2;
        $count = 0;
        $date = date('Y-m-d');
        $url = "www.xiaocai.ink/admin/auth/login";

        $sql = "SELECT ip,url,count(*) as num FROM action_log where date = '{$date}' and url like '%{$url}' GROUP BY ip ";
        $actions = DB::select($sql);
        $ins = [];
        //只查询当天的数据
        foreach ($actions as $action){
            if($action->num >= $max){
                $has = Blacklist::where('ip','=',$action->ip)->first();
                if($has){
                   continue;
                }
                $count++;
                //加入黑名单
                $ins[] = [
                    'ip'=>$action->ip,
                    'date'=>$date,
                    'created_at'=>date('Y-m-d H:i:s'),
                    'updated_at'=>date('Y-m-d H:i:s'),
                ];
            }
        }
        if($ins){
            DB::table('blacklist')->insert($ins);
        }

        return "黑名单加入了".$count;

    }





}
